#!/bin/sh
# OpsAgent init script from SAMPLE BASIC INIT SCRIPT
#
# Below is the chkconfig syntax for auto startup at different run levels
# Note runlevel 1 2 and 3, 69 is the Start order and 68 is the Stop order
# Also below is the description which is necessary.
#
# chkconfig: 2345 95 5
# description: OpsAgent
#
# Below is the source function library
#

. /etc/init.d/functions
#

AGENT_PID=<%= @run_path %>/datastax_agent.pid
AGENT_HOME=<%= @ops_path %>
AGENT_USER="cassandra"

export JAVA_HOME=<%= @java_path %>
export OPSC_CONF_DIR=<%= @conf_path %>
export PID=$AGENT_PID
export STARTUP_LOG=<%= @run_path %>/opsagent_startup.log

#
# Below is the Script Goodness controlling the service
#

start() {
  if [ -f $AGENT_PID ] && checkpid `cat $AGENT_PID`; then
    echo "OpsAgent is already running."
    exit 0
  fi

  echo -n $"Starting OpsAgent: "
  daemon --user $AGENT_USER $AGENT_HOME/bin/datastax-agent > $STARTUP_LOG 2>&1 
  usleep 500000
  RETVAL=$?
  if [ "$RETVAL" = "0" ]; then
    echo_success
  else
    echo_failure
  fi
  echo 
  return $RETVAL
}


stop() {
  # check if the process is already stopped by seeing if the pid file exists.
  if [ ! -f $AGENT_PID ]; then
    echo "OpsAgent is already stopped."
    exit 0
  fi
  echo -n $"Stopping OpsAgent "
  if kill `cat $AGENT_PID`; then
    RETVAL=0
    echo_success
  else
    RETVAL=1
    echo_failure
  fi
  echo
[ $RETVAL = 0 ]
}

status_fn() {
  if [ -f $AGENT_PID ] && checkpid `cat $AGENT_PID`; then
    echo "OpsAgent is running."
    exit 0
  else
    echo "OpsAgent is stopped."
    exit 1
  fi
}


case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  status)
    status_fn
    ;;
  restart)
    stop
    usleep 500000
    start
    ;;
  *)
    echo "Usage: $0 {start|stop|status|restart}"
    RETVAL=3
esac

exit $RETVAL

